package com.boot2.core.utils;

import com.boot2.core.exception.BusinessException;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * @author zhangweilin
 * @description:国际化消息资源读取工具
 * @date 2018/6/26
 */
public class MessageSourceUtil {

    /**
     * 最简单的获取
     * @param code
     * @param defaultMessage
     * @return
     */
    public static String getI18nMessage(String code) {
        return getI18nMessage(code, null, code);
    }

    /**
     * 最简单的获取
     * @param code
     * @param defaultMessage
     * @return
     */
    public static String getI18nMessage(String code,  String defaultMessage) {
        String i18nMessage = getI18nMessage(code, null, defaultMessage);
        return i18nMessage;
    }

    public static String getI18nMessage(String code, Object[] paramsArr, String defaultMessage) {
        MessageSource messageSource = SpringUtil.getBean(MessageSource.class);
        if (null != messageSource) {
            return getI18nMessage(messageSource, code, paramsArr,defaultMessage);
        }
        return defaultMessage;
    }

    /**
     * 读取国际化消息
     *
     * @param code
     * @param paramsArr
     * @return
     */
    public static String getI18nMessage(String code, Object[] paramsArr) {
        MessageSource messageSource = SpringUtil.getBean(MessageSource.class);
        if (null != messageSource) {
            return getI18nMessage(messageSource, code, paramsArr);
        }
        return code;
    }


    /**
     * 国际化，注意，此只能从message_xx.properties文件中读取国际化信息,而系统自带的校验框架,读取国际化信息只能从
     * ValidationMessages_xx.properties中读取
     *
     * @param messageSource
     * @param messageKey
     * @param params
     * @return
     */
    public static String getI18nMessage(MessageSource messageSource, String messageKey, Object[] params) {
        String message = "";
        try {
            Locale locale = LocaleContextHolder.getLocale();
            message = messageSource.getMessage(messageKey, params, locale);
        } catch (Exception e) {
            throw new BusinessException("获取国际化消息失败", e);
        }
        return message;
    }


    /**
     * 国际化，注意，此只能从message_xx.properties文件中读取国际化信息,而系统自带的校验框架,读取国际化信息只能从
     * * ValidationMessages_xx.properties中读取
     *
     * @param messageSource
     * @param messageKey
     * @param defaultMessage
     * @param params
     * @return
     */
    public static String getI18nMessage(MessageSource messageSource, String messageKey, Object[] params, String defaultMessage) {
        String message = "";
        try {
            Locale locale = LocaleContextHolder.getLocale();
            message = messageSource.getMessage(messageKey, params, defaultMessage, locale);
        } catch (Exception e) {
            throw new BusinessException("获取国际化消息失败", e);
        }
        return message;
    }
}
